#include "register.h"
#include "ui_register.h"
#include "./Common/config.h"
#include <QPushButton>
#include <QString>
#include <jsoncpp/json/json.h>
#include <QJsonObject>
#include <QJsonDocument>
#include <QMessageBox>

Register::Register(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Register)
{
    ui->setupUi(this);

    sql_management = new SQLManagement(g_host, g_user, g_passwd, g_database);
    doctor_management = new DoctorManagement(sql_management);
    patient_management = new PatientManagement(sql_management);

    connect(ui->register_btn, &QPushButton::clicked, this, &Register::register_btn_clicked);
    connect(ui->quit_btn, &QPushButton::clicked, this, &Register::quit_btn_clicked);
}

Register::~Register()
{
    delete ui;
}

void Register::register_btn_clicked()
{
    QString username = ui->name_ld->text();
    QString passwd = ui->passwd_ld->text();
    QString identity = ui->doctor_rbtn->isChecked() ? "doctor" : "patient";

    int age = ui->age_ld->text().isEmpty() ? -1 : ui->age_ld->text().toInt();
    QString gender = ui->gender_ld->text().isEmpty() ? "" : ui->gender_ld->text();
    QString phone = ui->phone_ld->text().isEmpty() ? "" : ui->phone_ld->text();
    QString address = ui->address_ld->text().isEmpty() ? "" : ui->address_ld->text();

    if (username.isEmpty() || passwd.isEmpty() || identity.isEmpty()) {
        Config::popMessageBox("WARNING", "必要消息未填写", "warning");
        return;
    }

    QJsonObject userInfo;
    userInfo["username"] = username;
    userInfo["password"] = passwd;
    userInfo["age"] = age;
    userInfo["gender"] = gender;
    userInfo["phone"] = phone;
    userInfo["address"] = address;

    LOG_DEBUG() << "identity : " << identity;

    if (identity == "doctor") {
        // 判断用户是否合法
        QString id = doctor_management->GetIdByName(username);
        if (doctor_management->isExist(id)) {
            Config::popMessageBox("WARNING", "用户名已存在", "warning");
            return; // 确保用户已经存在时停止继续执行
        }

        if (!doctor_management->Insert(userInfo)) {
            LOG_ERROR() << "insert doctor_management failed";
            Config::popMessageBox("ERROR", "注册失败", "error");
            return;
        }
    } else if (identity == "patient") {
        if (!patient_management->Insert(userInfo)) {
            LOG_ERROR() << "Insert patient_management failed";
            Config::popMessageBox("ERROR", "注册失败", "error");
            return;
        }
    }

    Config::popMessageBox("SUCCESS", "注册成功", "ok");
}

void Register::quit_btn_clicked()
{
    this->close();
}

